<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 2018/11/7
 * Time: 15:28
 */

namespace common\members\wodrow\tools;


class File
{
    /**
     * @param string $url 只能是类似这种的http://chedai.baozeqiche.com/Uploads/2018/11/154113098091120441.jpg
     * @return bool|string
     */
    public static function downloadTmpFileFromUrl($url)
    {
        $tmp_file = basename($url);
        $tmp_path = \Yii::getAlias("@tmp_root/{$tmp_file}");
        file_put_contents($tmp_path, file_get_contents($url));
        return $tmp_path;
    }

    /** 文件转base64输出
     * @param  String $file 文件路径
     * @return String base64 string
     */
    public static  function fileToBase64($file){
        $base64_file = '';
        if(file_exists($file)){
            $mime_type= mime_content_type($file);
            $base64_data = base64_encode(file_get_contents($file));
            $base64_file = 'data:'.$mime_type.';base64,'.$base64_data;
        }
        return $base64_file;
    }

    /**
     * base64去header
     * @param string $base64
     * @return string
     */
    public static function removeDataHeaderForBase64($base64)
    {
        $base64 = str_replace('data:image/jpeg;base64,', '', $base64);
        $base64 = str_replace('data:image/jpg;base64,', '', $base64);
        $base64 = str_replace('data:image/png;base64,', '', $base64);
        $base64 = str_replace('data:image/gif;base64,', '', $base64);
        return $base64;
    }
}